package com.servicesystem.servicesystem.service.impl;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.servicesystem.servicesystem.entity.douyin.Order;
import com.servicesystem.servicesystem.entity.douyin.vo.oauth.OauthVO;
import com.servicesystem.servicesystem.entity.douyin.vo.order.*;
import com.servicesystem.servicesystem.mapper.OrderMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.servicesystem.servicesystem.service.OrderService;
import com.servicesystem.servicesystem.untis.Http;
import io.netty.util.internal.StringUtil;
import org.apache.xmlbeans.impl.store.CharUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author X
 * @since 2020-09-11
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /***
     * 获取订单列表
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public String getOrderInfoList(String startTime, String endTime, String page, String size) throws Exception {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("end_time", endTime);
        linkedHashMap.put("order_by", "create_time");
        linkedHashMap.put("page", page);
        linkedHashMap.put("size", size);
        linkedHashMap.put("start_time", startTime);
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");


        String app_key = "6845190554020480520";
        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "order.list";
        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/order/list?app_key=" + app_key + "&access_token=" + access_token + "&method=order.list&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);


        Map resultMap = JSON.parseObject(result, Map.class);
        if (resultMap.get("err_no").equals(30002)) {
            String message = (String) resultMap.get("message");
            return message;
        }
        Object resultData = resultMap.get("data");
        System.out.println(resultData);

        /*测试*/
        JSONObject resultDataJson = JSONObject.parseObject(JSON.toJSONString(resultData));
        Map map1 = JSON.parseObject(JSON.toJSONString(resultDataJson), Map.class);
        Object list1 = map1.get("list");
        if (list1 == null) {
            return null;
        }

        List list = (List) map1.get("list");

        ArrayList<Order> orders = new ArrayList<>();
        for (Object listObj : list) {
            Order order = new Order();
            JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(listObj));
            Map map = JSON.parseObject(JSON.toJSONString(parseObject), Map.class);

            Object post_amount = map.get("post_amount");
            String post_amount_str = JSON.toJSONString(post_amount);
            order.setPostAmount(post_amount_str);
            String receipt_time = (String) map.get("receipt_time");
            order.setReceiptTime(receipt_time);
            String logistics_time = (String) map.get("logistics_time");
            order.setLogisticsTime(logistics_time);
            String cos_ratio = (String) map.get("cos_ratio");
            order.setCosRatio(cos_ratio);
            String user_name = (String) map.get("user_name");
            order.setUserName(user_name);
            Object urge_cnt = map.get("urge_cnt");
            String urge_cnt_str = JSON.toJSONString(urge_cnt);
            order.setUrgeCnt(urge_cnt_str);
            Object logistics_id = map.get("logistics_id");
            String logistics_id_str = JSON.toJSONString(logistics_id);
            order.setLogisticsId(logistics_id_str);
            Object shop_coupon_amount = map.get("shop_coupon_amount");
            String shop_coupon_amount_str = JSON.toJSONString(shop_coupon_amount);
            order.setShopCouponAmount(shop_coupon_amount_str);
            Object order_status = map.get("order_status");
            String order_status_str = JSON.toJSONString(order_status);
            order.setOrderStatus(order_status_str);
            Object update_time = map.get("update_time");
            String update_time_str = JSON.toJSONString(update_time);
            order.setUpdateTime(update_time_str);
            Object final_status = map.get("final_status");

            String is_comment = (String) map.get("is_comment");
            order.setIsComment(is_comment);
            String post_tel = (String) map.get("post_tel");
            order.setPostTel(post_tel);
            Object pay_type = map.get("pay_type");
            String pay_type_str = JSON.toJSONString(pay_type);
            order.setPayType(pay_type_str);
            String b_type = (String) map.get("b_type");
            order.setBType(b_type);
            Object order_type = map.get("order_type");
            String order_type_str = JSON.toJSONString(order_type);
            order.setOrderType(order_type_str);
            Object order_total_amount = map.get("order_total_amount");
            String order_total_amount_str = JSON.toJSONString(order_total_amount);
            order.setOrderTotalAmount(order_total_amount_str);
            Object coupon_amount = map.get("coupon_amount");
            String coupon_amount_str = JSON.toJSONString(coupon_amount);
            order.setCouponAmount(coupon_amount_str);
            String post_receiver = (String) map.get("post_receiver");
            order.setPostReceiver(post_receiver);
            String create_time = (String) map.get("create_time");
            order.setCreateTime(create_time);
            Object c_biz = map.get("c_biz");
            String c_biz_str = JSON.toJSONString(c_biz);
            order.setCBiz(c_biz_str);

            String logistics_code = (String) map.get("logistics_code");
            order.setLogisticsCode(logistics_code);
            String buyer_words = (String) map.get("buyer_words");
            order.setBuyerWords(buyer_words);
            Object coupon_info = map.get("coupon_info");

            String pay_time = (String) map.get("pay_time");
            order.setPayTime(pay_time);
            Object shop_id_obj = map.get("shop_id");
            String shop_id_str = JSON.toJSONString(shop_id_obj);
            order.setShopId(shop_id_str);
            String cancel_reason = (String) map.get("cancel_reason");
            order.setCancelReason(cancel_reason);
            Object exp_ship_time = map.get("exp_ship_time");
            String exp_ship_time_str = JSON.toJSONString(exp_ship_time);
            order.setExpShipTime(exp_ship_time_str);
            Object seller_words = map.get("seller_words");
            String seller_words_str = JSON.toJSONString(seller_words);
            order.setSellerWords(seller_words_str);
            String c_type = (String) map.get("c_type");

            String post_code = (String) map.get("post_code");
            order.setPostCode(post_code);
            Object child_num = map.get("child_num");
            String child_num_str = JSON.toJSONString(child_num);
            order.setChildNum(child_num_str);
            String order_id = (String) map.get("order_id");
//            order.setOrderId(order_id);
            order.setPid(order_id);
            Object child = map.get("child");
            String child_str = JSON.toJSONString(child);
            order.setChild(child_str);

            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("pid", order_id);
            Integer integer = baseMapper.selectCount(orderQueryWrapper);
            if (integer == 0) {
                List child2 = (List) map.get("child");
                System.out.println("child2..." + child2);
                for (Object childObj : child2) {
                    JSONObject childObject = JSONObject.parseObject(JSON.toJSONString(childObj));
                    Map childObjectMap = JSON.parseObject(JSON.toJSONString(childObject), Map.class);
                    Object orderIdObj = childObjectMap.get("order_id");
                    String orderIdStr = JSON.toJSONString(orderIdObj);
                    order.setOrderId(orderIdStr.replaceAll("\"", ""));
                    Object comboAmount = childObjectMap.get("combo_amount");
                    String comboAmountStr = JSON.toJSONString(comboAmount);
                    System.out.println("comboAmountStr..." + comboAmountStr);
                    order.setComboAmount(comboAmountStr);
                    Object comboNum = childObjectMap.get("combo_num");
                    String comboNumStr = JSON.toJSONString(comboNum);
                    order.setComboNum(comboNumStr);
                    Object productId = childObjectMap.get("product_id");
                    String productIdStr = JSON.toJSONString(productId);
                    order.setProductId(productIdStr);
                    Object comboId = childObjectMap.get("combo_id");
                    String comboIdStr = JSON.toJSONString(comboId);
                    order.setComboId(comboIdStr);
                    Object totalAmount = childObjectMap.get("total_amount");
                    String totalAmountStr = JSON.toJSONString(totalAmount);
                    order.setTotalAmount(totalAmountStr);

                    Object postAddr = childObjectMap.get("post_addr");
                    PostAddrVO postAddrVO = JSON.parseObject(JSON.toJSONString(postAddr), PostAddrVO.class);
                    order.setDetail(postAddrVO.getDetail());
                    City city = postAddrVO.getCity();
                    order.setCityName(city.getName());
                    Province province = postAddrVO.getProvince();
                    order.setProvinceName(province.getName());
                    Town town = postAddrVO.getTown();
                    order.setTownName(town.getName());

                    Object product_pic_str = childObjectMap.get("product_pic");
                    String productPic = JSON.toJSONString(product_pic_str);
                    order.setProductPic(productPic);
                    Object product_name_str = childObjectMap.get("product_name");
                    String productName = JSON.toJSONString(product_name_str);
                    System.out.println("productName..." + productName);
                    order.setProductName(productName);

                    int insert = baseMapper.insert(order);
                    orders.add(order);
                }
            } else {
                List child2 = (List) map.get("child");
                System.out.println("child2..." + child2);
                for (Object childObj : child2) {
                    JSONObject childObject = JSONObject.parseObject(JSON.toJSONString(childObj));
                    Map childObjectMap = JSON.parseObject(JSON.toJSONString(childObject), Map.class);
                    Object orderIdObj = childObjectMap.get("order_id");
                    String orderIdStr = JSON.toJSONString(orderIdObj);
                    order.setOrderId(orderIdStr.replaceAll("\"", ""));
                    Object comboAmount = childObjectMap.get("combo_amount");
                    String comboAmountStr = JSON.toJSONString(comboAmount);
                    System.out.println("comboAmountStr..." + comboAmountStr);
                    order.setComboAmount(comboAmountStr);
                    Object comboNum = childObjectMap.get("combo_num");
                    String comboNumStr = JSON.toJSONString(comboNum);
                    order.setComboNum(comboNumStr);
                    Object productId = childObjectMap.get("product_id");
                    String productIdStr = JSON.toJSONString(productId);
                    order.setProductId(productIdStr);
                    Object comboId = childObjectMap.get("combo_id");
                    String comboIdStr = JSON.toJSONString(comboId);
                    order.setComboId(comboIdStr);
                    Object totalAmount = childObjectMap.get("total_amount");
                    String totalAmountStr = JSON.toJSONString(totalAmount);
                    order.setTotalAmount(totalAmountStr);

                    Object postAddr = childObjectMap.get("post_addr");
                    PostAddrVO postAddrVO = JSON.parseObject(JSON.toJSONString(postAddr), PostAddrVO.class);
                    order.setDetail(postAddrVO.getDetail());
                    City city = postAddrVO.getCity();
                    order.setCityName(city.getName());
                    Province province = postAddrVO.getProvince();
                    order.setProvinceName(province.getName());
                    Town town = postAddrVO.getTown();
                    order.setTownName(town.getName());

                    Object product_pic_str = childObjectMap.get("product_pic");
                    String productPic = JSON.toJSONString(product_pic_str);
                    order.setProductPic(productPic);
                    Object product_name_str = childObjectMap.get("product_name");
                    String productName = JSON.toJSONString(product_name_str);
                    System.out.println("productName..." + productName);
                    order.setProductName(productName);

                    QueryWrapper<Order> orderQueryWrapper1 = new QueryWrapper<>();
                    orderQueryWrapper1.eq("pid", order_id);
                    int insert = baseMapper.update(order, orderQueryWrapper1);
                    orders.add(order);
                }
            }
        }

        /*返回数据*/
        JSONObject resultDataJsonObject = JSONObject.parseObject(JSON.toJSONString(resultData));
        String resultDataJsonObjectStr = JSON.toJSONString(resultDataJsonObject);
        return resultDataJsonObjectStr;
    }

    /***
     * 查看订单中有多少没有评论数量
     * @return
     */
    @Override
    public int getIsCommentCount() {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("is_comment", 0);
        Integer integer = baseMapper.selectCount(orderQueryWrapper);
        return integer;
    }

    /***
     * 给未评价的用户发送短信
     * @return
     */
    @Override
    public int sendSMS() {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("is_comment", 0);
        List<Order> orders = baseMapper.selectList(orderQueryWrapper);
        for (Order order : orders) {
            String postTel = order.getPostTel();
            String result = null;
            String url = "http://v.juhe.cn/sms/send";//请求接口地址
            Map params = new HashMap();//请求参数
            params.put("mobile", postTel);//接受短信的用户手机号码
            params.put("tpl_id", "178493");//您申请的短信模板ID，根据实际情况修改
//            params.put("tpl_value", "#code#=" + "666");//您设置的模板变量，根据实际情况修改
            params.put("key", "5829b6c962f915b1c637038e9eb971ad");//应用APPKEY(应用详细页查询)
            try {
                result = net(url, params, "GET");
                net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(result);
                if (object.getInt("error_code") == 0) {
                    System.out.println(object.get("result"));
                } else {
                    System.out.println(object.get("error_code") + ":" + object.get("reason"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 1;
    }

    /***
     * 订单处理 获取订单列表
     * @return
     */
    @Override
    public Page<Order> getOrderList(Page<Order> orderPage, Order order) {
//        baseMapper.selectPage(orderPage, null);
        baseMapper.getOrderList(orderPage, order);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rows", orderPage.getRecords());
        map.put("current", orderPage.getCurrent());
        map.put("pages", orderPage.getPages());
        map.put("size", orderPage.getSize());
        map.put("total", orderPage.getTotal());
        map.put("hasNext", orderPage.hasNext());
        map.put("hasPrevious", orderPage.hasPrevious());
        return orderPage;
    }

    /***
     * 给未评价的用户发送短信 个人
     * @param phone
     * @return
     */
    @Override
    public int sendPhoneSMS(String phone) {
        String result = null;
        String url = "http://v.juhe.cn/sms/send";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("mobile", phone);//接受短信的用户手机号码
        params.put("tpl_id", "178493");//您申请的短信模板ID，根据实际情况修改
//        params.put("tpl_value", "#code#=" + "666");//您设置的模板变量，根据实际情况修改
        params.put("key", "5829b6c962f915b1c637038e9eb971ad");//应用APPKEY(应用详细页查询)
        try {
            result = net(url, params, "GET");
            net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(result);
            if (object.getInt("error_code") == 0) {
                System.out.println(object.get("result"));
            } else {
                System.out.println(object.get("error_code") + ":" + object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    /***
     * 获取订单 TODO
     * @param orderId
     * @return
     */
    @Override
    public String getOrderOne(String orderId) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("order_id", orderId);
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");


        String app_key = "6845190554020480520";
        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "order.detail";
        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/order/detail?app_key=" + app_key + "&access_token=" + access_token + "&method=order.detail&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);

        Map resultMap = JSON.parseObject(result, Map.class);
        Object resultData = resultMap.get("data");
        System.out.println(resultData);

        /*测试*/
        JSONObject resultDataJson = JSONObject.parseObject(JSON.toJSONString(resultData));
        Map map1 = JSON.parseObject(JSON.toJSONString(resultDataJson), Map.class);
        Object list1 = map1.get("list");
        if (list1 == null) {
            return null;
        }
        List list = (List) map1.get("list");

        for (Object listObj : list) {
            Order order = new Order();
            JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(listObj));
            Map map = JSON.parseObject(JSON.toJSONString(parseObject), Map.class);

            String receipt_time = (String) map.get("receipt_time");
            order.setReceiptTime(receipt_time);
            String logistics_time = (String) map.get("logistics_time");
            order.setLogisticsTime(logistics_time);

            Object logistics_id = map.get("logistics_id");
            String logistics_id_str = JSON.toJSONString(logistics_id);
            order.setLogisticsId(logistics_id_str);
            String logistics_code = (String) map.get("logistics_code");
            order.setLogisticsCode(logistics_code);

            Object order_status = map.get("order_status");
            String order_status_str = JSON.toJSONString(order_status);
            order.setOrderStatus(order_status_str);
            Object update_time = map.get("update_time");
            String update_time_str = JSON.toJSONString(update_time);
            order.setUpdateTime(update_time_str);
            order.setShipStatus("2");

            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("pid", orderId);
            int insert = baseMapper.update(order, orderQueryWrapper);
        }
        return result;
    }

    /***
     * 订单发货
     * @param orderLogisticsAddVO
     * @return
     */
    @Override
    public String orderLogisticsAdd(OrderLogisticsAddVO orderLogisticsAddVO) throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("company", orderLogisticsAddVO.getCompany());
        linkedHashMap.put("logistics_code", orderLogisticsAddVO.getLogisticsCode());
        linkedHashMap.put("logistics_id", orderLogisticsAddVO.getLogisticsId());
        linkedHashMap.put("order_id", orderLogisticsAddVO.getOrderId());
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");


        String app_key = "6845190554020480520";
        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "order.logisticsAdd";
        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/order/logisticsAdd?app_key=" + app_key + "&access_token=" + access_token + "&method=order.logisticsAdd&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取快递公司列表
     * @return
     */
    @Override
    public String logisticsCompanyList() throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(null, null);
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");


        String app_key = "6845190554020480520";
        String shop_id = "173078";
        //通过redis获取access_token
        String oauth = stringRedisTemplate.boundValueOps(shop_id).get();
        OauthVO oauthVO = JSON.parseObject(oauth, OauthVO.class);
        String access_token = oauthVO.getAccess_token();

        String method = "order.logisticsCompanyList";
        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/order/logisticsCompanyList?app_key=" + app_key + "&access_token=" + access_token + "&method=order.logisticsCompanyList&param_json=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 1688发货成功修改发货状态
     * @param orderId
     */
    @Override
    public void upDataOrderOrderStatus(String orderId) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_id", orderId);
        Order order = new Order();
        order.setShipStatus("1");
        int update = baseMapper.update(order, orderQueryWrapper);

    }

    /***
     * 消息订阅 订单创建
     * @param
     * @return
     */
    /*@Override
    public Order tradeTradeCreate(String pId) throws UnsupportedEncodingException {
        String orderId = pId + "A";
        String orderResult = this.getOrderOne(orderId);
        //判断订单中是否有该订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_id", orderId);
        Integer integer = baseMapper.selectCount(orderQueryWrapper);
        if (integer == 0) {
            //解析
            Order parsing = this.parsing(orderResult);
            int insert = baseMapper.insert(parsing);
        }
        return null;
    }*/
    public String sign(String app_key, String mapStr, String method, String format2) {
        String secret = "8963b551-bd04-4be5-b02b-2e82ee0fccdb";
        String str = secret + "app_key" + app_key + "method" + method + "param_json" + mapStr + "timestamp" + format2 + "v2" + secret;
        String res = stringToMD5(str);
        return res;
    }

    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
        while (md5code.length() < 32) {
            md5code.insert(0, "0");
        }
        return md5code.toString();
    }

    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public Order parsing(String result) {
        Map resultMap = JSON.parseObject(result, Map.class);
        Object resultData = resultMap.get("data");
        System.out.println(resultData);

        /*测试*/
        JSONObject resultDataJson = JSONObject.parseObject(JSON.toJSONString(resultData));
        Map map1 = JSON.parseObject(JSON.toJSONString(resultDataJson), Map.class);
        Object list1 = map1.get("list");
        if (list1 == null) {
            return null;
        }

        List list = (List) map1.get("list");
        Order order = new Order();
        for (Object listObj : list) {
            JSONObject parseObject = JSONObject.parseObject(JSON.toJSONString(listObj));
            Map map = JSON.parseObject(JSON.toJSONString(parseObject), Map.class);

            Object post_amount = map.get("post_amount");
            String post_amount_str = JSON.toJSONString(post_amount);
            order.setPostAmount(post_amount_str);
            String receipt_time = (String) map.get("receipt_time");
            order.setReceiptTime(receipt_time);
            String logistics_time = (String) map.get("logistics_time");
            order.setLogisticsTime(logistics_time);
            String cos_ratio = (String) map.get("cos_ratio");
            order.setCosRatio(cos_ratio);
            String user_name = (String) map.get("user_name");
            order.setUserName(user_name);
            Object urge_cnt = map.get("urge_cnt");
            String urge_cnt_str = JSON.toJSONString(urge_cnt);
            order.setUrgeCnt(urge_cnt_str);
            Object logistics_id = map.get("logistics_id");
            String logistics_id_str = JSON.toJSONString(logistics_id);
            order.setLogisticsId(logistics_id_str);
            Object shop_coupon_amount = map.get("shop_coupon_amount");
            String shop_coupon_amount_str = JSON.toJSONString(shop_coupon_amount);
            order.setShopCouponAmount(shop_coupon_amount_str);
            Object order_status = map.get("order_status");
            String order_status_str = JSON.toJSONString(order_status);
            order.setOrderStatus(order_status_str);
            Object update_time = map.get("update_time");
            String update_time_str = JSON.toJSONString(update_time);
            order.setUpdateTime(update_time_str);
            Object final_status = map.get("final_status");

            String is_comment = (String) map.get("is_comment");
            order.setIsComment(is_comment);
            String post_tel = (String) map.get("post_tel");
            order.setPostTel(post_tel);
            Object pay_type = map.get("pay_type");
            String pay_type_str = JSON.toJSONString(pay_type);
            order.setPayType(pay_type_str);
            String b_type = (String) map.get("b_type");
            order.setBType(b_type);
            Object order_type = map.get("order_type");
            String order_type_str = JSON.toJSONString(order_type);
            order.setOrderType(order_type_str);
            Object order_total_amount = map.get("order_total_amount");
            String order_total_amount_str = JSON.toJSONString(order_total_amount);
            order.setOrderTotalAmount(order_total_amount_str);
            Object coupon_amount = map.get("coupon_amount");
            String coupon_amount_str = JSON.toJSONString(coupon_amount);
            order.setCouponAmount(coupon_amount_str);
            String post_receiver = (String) map.get("post_receiver");
            order.setPostReceiver(post_receiver);
            String create_time = (String) map.get("create_time");
            order.setCreateTime(create_time);
            Object c_biz = map.get("c_biz");
            String c_biz_str = JSON.toJSONString(c_biz);
            order.setCBiz(c_biz_str);

            String logistics_code = (String) map.get("logistics_code");
            order.setLogisticsCode(logistics_code);
            String buyer_words = (String) map.get("buyer_words");
            order.setBuyerWords(buyer_words);
            Object coupon_info = map.get("coupon_info");

            String pay_time = (String) map.get("pay_time");
            order.setPayTime(pay_time);
            Object shop_id_obj = map.get("shop_id");
            String shop_id_str = JSON.toJSONString(shop_id_obj);
            order.setShopId(shop_id_str);
            String cancel_reason = (String) map.get("cancel_reason");
            order.setCancelReason(cancel_reason);
            Object exp_ship_time = map.get("exp_ship_time");
            String exp_ship_time_str = JSON.toJSONString(exp_ship_time);
            order.setExpShipTime(exp_ship_time_str);
            Object seller_words = map.get("seller_words");
            String seller_words_str = JSON.toJSONString(seller_words);
            order.setSellerWords(seller_words_str);
            String c_type = (String) map.get("c_type");

            String post_code = (String) map.get("post_code");
            order.setPostCode(post_code);
            Object child_num = map.get("child_num");
            String child_num_str = JSON.toJSONString(child_num);
            order.setChildNum(child_num_str);
            String order_id = (String) map.get("order_id");
            order.setOrderId(order_id);
            Object child = map.get("child");
            String child_str = JSON.toJSONString(child);
            order.setChild(child_str);

            List child2 = (List) map.get("child");
            System.out.println("child2..." + child2);
            for (Object childObj : child2) {
                JSONObject childObject = JSONObject.parseObject(JSON.toJSONString(childObj));
                Map childObjectMap = JSON.parseObject(JSON.toJSONString(childObject), Map.class);
                Object comboAmount = childObjectMap.get("combo_amount");
                String comboAmountStr = JSON.toJSONString(comboAmount);
                System.out.println("comboAmountStr..." + comboAmountStr);
                order.setComboAmount(comboAmountStr);
                Object comboNum = childObjectMap.get("combo_num");
                String comboNumStr = JSON.toJSONString(comboNum);
                order.setComboNum(comboNumStr);
                Object productId = childObjectMap.get("product_id");
                String productIdStr = JSON.toJSONString(productId);
                order.setProductId(productIdStr);
                Object comboId = childObjectMap.get("combo_id");
                String comboIdStr = JSON.toJSONString(comboId);
                order.setComboId(comboIdStr);
                Object totalAmount = childObjectMap.get("total_amount");
                String totalAmountStr = JSON.toJSONString(totalAmount);
                order.setTotalAmount(totalAmountStr);

                Object postAddr = childObjectMap.get("post_addr");
                PostAddrVO postAddrVO = JSON.parseObject(JSON.toJSONString(postAddr), PostAddrVO.class);
                order.setDetail(postAddrVO.getDetail());
                City city = postAddrVO.getCity();
                order.setCityName(city.getName());
                Province province = postAddrVO.getProvince();
                order.setProvinceName(province.getName());
                Town town = postAddrVO.getTown();
                order.setTownName(town.getName());

                Object product_pic_str = childObjectMap.get("product_pic");
                String productPic = JSON.toJSONString(product_pic_str);
                order.setProductPic(productPic);
                Object product_name_str = childObjectMap.get("product_name");
                String productName = JSON.toJSONString(product_name_str);
                System.out.println("productName..." + productName);
                order.setProductName(productName);
            }
        }
        return order;
    }
}
